# coding: utf8
import sys

import os

res_path = "/Applications/MyVpn.app/Contents/Resources/myvpn/"
state_file = "/var/tmp/myvpn.state"

plist = '''<plist version="1.0">
        <dict>
                <key>Label</key>
                <string>%s</string>
                <key>ProgramArguments</key>
                <array>
                        <string>%s</string>
                        <string>%s</string>
                </array>
                <key>RunAtLoad</key>
                <true></true>
                <key>KeepAlive</key>
                <true/>
                <key>StandardOutPath</key>
                <string>/var/log/%s</string>
                <key>StandardErrorPath</key>
                <string>/var/log/%s</string>
                <key>WorkingDirectory</key>
                <string>%s</string>
        </dict>
</plist>'''


def execute(cmd):
    ret = os.popen(cmd).read().strip()
    return ret


def get_vpn_state():
    vpn_state = "absent"
    tmp = execute("ps aux | grep \"myvpn \" | grep -v grep")
#     print tmp
    if tmp:
        with open(state_file) as f:
            vpn_state = f.read().strip().lower()
    return vpn_state


def get_dns_state():
    return "running" if execute("ps aux | grep python | grep dns_client | grep -v grep") else "absent"


if __name__ == '__main__':
# print get_dns_state()

# if False:
    f = sys.argv[1]

    if f == "state":
        print "%s|%s" % (get_vpn_state(), get_dns_state())
        exit()

    if not os.path.exists('/Library/LaunchDaemons/myvpn.start.plist'):
        pcontent = plist % ('MyVpn.start',
                            res_path + 'myvpn',
                            res_path + 'dns_proxy.conf',
                            'myvpn.log',
                            'myvpn.log',
                            res_path,
                            )
        with open('/Library/LaunchDaemons/myvpn.start.plist', 'w') as f:
            f.write(pcontent)

    if not os.path.exists('/Library/LaunchDaemons/dnsproxy.start.plist'):
        pcontent = plist % ('DnsProxy.start',
                            'python',
                            res_path + 'dns_proxy.py',
                            'dnsproxy.log',
                            'dnsproxy.log',
                            res_path,
                            )
        with open('/Library/LaunchDaemons/dnsproxy.start.plist', 'w') as f:
            f.write(pcontent)

    if f == "启用/禁用VPN":
        if get_vpn_state() == 'absent':
            os.popen("""
launchctl load -w /Library/LaunchDaemons/myvpn.start.plist
""")
        else:
            os.popen("""
launchctl unload -w /Library/LaunchDaemons/myvpn.start.plist
""")
    if f == "启用/禁用DNS":
        if get_dns_state() == 'absent':
            os.popen("""
launchctl load -w /Library/LaunchDaemons/dnsproxy.start.plist
""")
        else:
            os.popen("""
launchctl unload -w /Library/LaunchDaemons/dnsproxy.start.plist
""")
